package com.clouddot.baipai.ui.fragment.H_MainFragment;

import android.content.Context;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Spanned;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.VideoView;

import com.bumptech.glide.Glide;
import com.clouddot.baipai.R;
import com.clouddot.baipai.infrastructure.environment.Env;
import com.clouddot.baipai.model.beam.getArcticList.ariticInfo;
import com.clouddot.baipai.model.beam.getArcticList.getArcticListResponse;
import com.clouddot.baipai.model.beam.getSchoolInfo.getSchoolInfoResponse;
import com.clouddot.baipai.ui.activity.H_SMainActivity;
import com.clouddot.baipai.ui.adapter.H_Adapter.schoolRecyclerAdapter;
import com.clouddot.baipai.ui.dialog.H_Dialog.H_FoodDailog;
import com.clouddot.baipai.ui.fragment.BaseFragment;
import com.clouddot.baipai.ui.util.EscapeUnescapeUtil;
import com.clouddot.baipai.ui.util.ToastUtil;
import com.danikula.videocache.HttpProxyCacheServer;
import com.danikula.videocache.file.FileNameGenerator;
import com.xiao.nicevideoplayer.NiceVideoPlayer;
import com.xiao.nicevideoplayer.NiceVideoPlayerManager;
import com.xiao.nicevideoplayer.TxVideoPlayerController;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wxy on 2018/4/10.
 */

public class H_SchoolFragment extends BaseFragment {
    private View view;
    private Context context;
    private String CurrentItem;
    private TextView name;
    private ImageView imageView1;
    private WebView tvContent1;
    private ScrollView constraintLayout4 ;
    private Animation animation;
    private ScrollView constraintLayout1;
    private ConstraintLayout constraintLayout2;
    private RelativeLayout relativeLayout;
    private RecyclerView recyclerView2;
    private schoolRecyclerAdapter schoolRecyclerAdapter;
    private List<ariticInfo> lists = new ArrayList<ariticInfo>();

    private Boolean isRunning = false;
    private int CurrentPage = 1;
    private NiceVideoPlayer VideoView;
    private HttpProxyCacheServer proxy;
    private String videoPath;
    private TxVideoPlayerController controller;


    public HttpProxyCacheServer getProxy() {
        return proxy == null ? (proxy = newProxy()) : proxy;
    }

    private HttpProxyCacheServer newProxy() {
        return  new HttpProxyCacheServer.Builder(getActivity())
                .maxCacheSize(1024 * 1024 * 1024)
                .fileNameGenerator(new MyFileNameGenerator())
                .build();
    }

    public class MyFileNameGenerator implements FileNameGenerator {
        public String generate(String url) {
            return "/BanPai" + videoPath;
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        return view;
    }

    @Override
    protected void setContentView() {
        super.setContentView();

        view = LayoutInflater.from(context).inflate(R.layout.h_f_schoolfg,null);
    }

    @Override
    protected void initControls() {
        super.initControls();
        recyclerView2 = view.findViewById(R.id.recycle2);
        recyclerView2.setLayoutManager(new LinearLayoutManager(context));
        recyclerView2.setItemAnimator(new DefaultItemAnimator());
        schoolRecyclerAdapter = new schoolRecyclerAdapter(context,lists);
        recyclerView2.setAdapter(schoolRecyclerAdapter);

        animation = AnimationUtils.loadAnimation(context,R.anim.buttom_click_anim);
        animation.setDuration(200);

        tvContent1 =  view.findViewById(R.id.tvContent);

        name = view.findViewById(R.id.name);
        imageView1 = view.findViewById(R.id.img);
        VideoView = view.findViewById(R.id.VideoView);
        controller = new TxVideoPlayerController(getActivity());

        constraintLayout4 = view.findViewById(R.id.content2);

        constraintLayout1 = view.findViewById(R.id.left);
        constraintLayout2 = view.findViewById(R.id.right);

        constraintLayout1.startAnimation(animation1);
        constraintLayout2.startAnimation(animation2);

        relativeLayout = view.findViewById(R.id.loading);
        ImageView loading = view.findViewById(R.id.imgloading);
        loading.startAnimation(loadingAnim);

    }

    @Override
    protected void setListener() {
        super.setListener();
    }

    @Override
    protected void loadParams() {
        super.loadParams();
    }

    @Override
    public void onAttach(Context context) {
        this.context = context;
        super.onAttach(context);
    }

    private void init(String mVideoUrl,String title) {


    }

    @Override
    public void onStop() {
        NiceVideoPlayerManager.instance().releaseNiceVideoPlayer();
        super.onStop();
    }

    @Override
    public void onResume() {
        super.onResume();
        if(Env.getAppContext().isInitial) {
            constraintLayout4.setVisibility(View.GONE);
            relativeLayout.setVisibility(View.VISIBLE);
            runThreadAction("SchoolInfo");
        }

    }


    @Override
    public void runThreadAction(String actionName) {
        super.runThreadAction(actionName);

    }

    @Override
    protected Object runThreadActionExceute(String actionName) {
        super.runThreadActionExceute(actionName);
        if(actionName.matches("SchoolInfo")){
            return Env.getAppPresenter().getArcticList(actionName,CurrentPage,Env.getAppContext().itemCount);
        }  else {
            return Env.getAppPresenter().getSchoolInfo(actionName);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected void runThreadActionSuccess(String actionName, Object result) {
        super.runThreadActionSuccess(actionName, result);

            if(actionName.matches("SchoolInfo")) {
            getArcticListResponse response = (getArcticListResponse) result;
            if(response.list.isEmpty()){
                ToastUtil.showToast(getActivity(),"学校栏目为空");
                return ;
            }else{
                lists = response.list;
                lists.get(0).flag = true;
                CurrentItem = lists.get(0).getTitle();
                schoolRecyclerAdapter = new schoolRecyclerAdapter(context,lists);
                schoolRecyclerAdapter.setbtnOnclicker(new schoolRecyclerAdapter.btnOnclicker() {
                    @Override
                    public void onClicked(int position) {
                        H_SMainActivity.backTime = Env.getAppContext().backMainTime * 60;
                        if(isRunning) {
                            constraintLayout4.setVisibility(View.GONE);
                            relativeLayout.setVisibility(View.VISIBLE);
                            NiceVideoPlayerManager.instance().releaseNiceVideoPlayer();
                            tvContent1.setVisibility(View.GONE);
                            imageView1.setVisibility(View.GONE);
                            VideoView.setVisibility(View.GONE);
                            name.setText(lists.get(position).getTitle());
                            isRunning = false;
                            for (ariticInfo courseInfo : lists) {
                                courseInfo.flag = false;
                            }
                            lists.get(position).flag = true;
                            schoolRecyclerAdapter.notifyDataSetChanged();
                            CurrentItem =lists.get(position).getTitle();
                            runThreadAction(CurrentItem);
                        }
                    }
                });
                recyclerView2.setAdapter(schoolRecyclerAdapter);
                name.setText(lists.get(0).getTitle());
                runThreadAction(CurrentItem);
            }
        } else {
            getSchoolInfoResponse response = (getSchoolInfoResponse) result;
            if (response.isSuccess()) {
                constraintLayout4.setVisibility(View.VISIBLE);
                if (CurrentItem.equals(actionName)) {
                    if(response.url != null) {
                        imageView1.setVisibility(View.VISIBLE);
                        Glide.with(context).load(response.url).placeholder(R.drawable.imageload).error(R.drawable.imagefail).into(imageView1);
                    }
                    if(response.ArticleData != null && response.ArticleData.getContent() != null) {
                        final String html = EscapeUnescapeUtil.unescape(response.ArticleData.getContent());
                        tvContent1.setBackgroundColor(0);
                        tvContent1.getSettings().setDefaultTextEncodingName("UTF -8");
                        tvContent1.loadData(html, "text/html; charset=UTF-8", null);
                        tvContent1.setVisibility(View.VISIBLE);
                    }
                    if(response.VideoData != null && !response.VideoData.isEmpty()){
                        videoPath = response.VideoData.get(0).RealPathName;
                        String url = Env.getAppContext().IP + response.VideoData.get(0).RealPathName;
                        String imageUrl = Env.getAppContext().IP + response.imageurl;
                        String title = actionName;
                        Log.i( "refluesShcoolInfo: ",url);
                        String proxyUrl = getProxy().getProxyUrl(url);
                        VideoView.setPlayerType(NiceVideoPlayer.TYPE_IJK); // or NiceVideoPlayer.TYPE_NATIVE
                        VideoView.setUp(url, null);
                        controller.setTitle(title);
                        VideoView.setController(controller);
                        VideoView.setVisibility(View.VISIBLE);


//                        VideoView.setVideoPath(proxyUrl);
//
//                        VideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
//                            @Override
//                            public void onCompletion(MediaPlayer mp) {
//                                VideoView.start();
//                            }
//                        });
//                        VideoView.requestFocus();
//                        VideoView.start();
                    }
                }

            } else {
                ToastUtil.showToast(context,response.getErrMsg());
                isRunning = true;
                return;
            }
        }
        relativeLayout.setVisibility(View.GONE);
        isRunning = true;
    }

    @Override
    protected void runThreadActionError(String actionName, Exception ex) {
        super.runThreadActionError(actionName, ex);
    }
}
